package svgedit.japangui.actions;

import java.awt.event.ActionEvent;
import java.io.File;
import javax.swing.AbstractAction;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;

import svgedit.gui.SVGFileFilter;
import svgedit.japangui.JapanFrame;

/** Shows a file dialog for the user to select a new file to write the document
 *  to, then saves it at that location.
 */
@SuppressWarnings("serial")
public class SaveDocumentAsAction extends AbstractAction {

    private JapanFrame japanFrame;

    /** Create this action for the given frame */
    public SaveDocumentAsAction(JapanFrame japanFrame) {
        super("\u4FDD\u5b58\u3059\u308B\u3068...");
        this.japanFrame = japanFrame;
    }

    public void actionPerformed(ActionEvent arg0) {
        File file = japanFrame.getDocument().getFile();
        JFileChooser dialog;
        if (file != null)
            dialog = new JFileChooser(file);
        else
            dialog = new JFileChooser(japanFrame.getPreferences().getDefaultPath());
        dialog.addChoosableFileFilter(new SVGFileFilter());
        dialog.showSaveDialog(null);

        file = dialog.getSelectedFile();
		if (file.getName().toLowerCase().endsWith(".svgz")) {
			if (file != null) {
				if (file.exists()) {
					if (JOptionPane.showConfirmDialog(japanFrame.getRootPane(),
							String.format("\u3042\u306A\u305f\u304C%s\u3068\u3044\u3046\u540D\u524D\u306E\u65E2\u5b58\u306E\u30D5\u30A1\uFF72\uFF99\u3092\u7f6e\u304D\63db\u3048\u307e\u3059\u304B?",
									file.getName()), "\u4E0A\u66F8\u304D\u65E2\u5b58\u306E\u30D5\u30A1\uFF72\uFF99\u3092?",
									JOptionPane.OK_CANCEL_OPTION) == JOptionPane.CANCEL_OPTION)
						return;
				}
				japanFrame.getPreferences().setDefaultPath(file.getPath());
				
				// Create a temporary file to export it to svgz
				japanFrame.saveFile(new File (".\\temp.svg"));
				File temp = new File(".\\temp.svg");
				japanFrame.saveSVGZ(file,temp);
			}

		}
		else {
			if (file != null) {
				if (file.exists()) {
					if (JOptionPane.showConfirmDialog(japanFrame.getRootPane(),
							String.format("\u3042\u306A\u305f\u304C%s\u3068\u3044\u3046\u540D\u524D\u306E\u65E2\u5b58\u306E\u30D5\u30A1\uFF72\uFF99\u3092\u7f6e\u304D\63db\u3048\u307e\u3059\u304B?",
									file.getName()), "\u4E0A\u66F8\u304D\u65E2\u5b58\u306E\u30D5\u30A1\uFF72\uFF99\u3092?",
									JOptionPane.OK_CANCEL_OPTION) == JOptionPane.CANCEL_OPTION)
						return;
				}
				japanFrame.getPreferences().setDefaultPath(file.getPath());
				japanFrame.saveFile(file);
			}
		}
    }

}
